<template>
  <div class="home-container">
    <!-- 左侧备考进度区域 -->
    <div class="progress-container">
      <div class="progress-card">
        <div class="progress-header">
          <el-icon class="calendar-icon"><Calendar /></el-icon>
          <span class="progress-title">26考研备战进度</span>
        </div>
        
        <div class="progress-content">
          <div class="timeline">
            <!-- 2月基础准备阶段 -->
            <div class="timeline-item" :class="{'active': currentStage === 'preparation'}">
              <div class="timeline-dot dot-blue"></div>
              <div class="timeline-date">2025年2月</div>
              <div class="timeline-stage">
                <span class="stage-title">基础准备阶段</span>
                <ul class="stage-tasks">
                  <li>确定目标院校</li>
                  <li>收集复习资料</li>
                  <li>制定全年复习计划</li>
                </ul>
              </div>
            </div>
                
            <!-- 3-6月第一轮复习 -->
            <div class="timeline-item" :class="{'active': currentStage === 'first-review'}">
              <div class="timeline-dot dot-green"></div>
              <div class="timeline-date">2025年3-6月</div>
              <div class="timeline-stage">
                <span class="stage-title">第一轮复习</span>
                <ul class="stage-tasks">
                  <li>英语/数学基础夯实</li>
                  <li>专业课初步梳理</li>
                  <li>完成基础教材学习</li>
                </ul>
              </div>
            </div>
                
            <!-- 7-8月暑期强化 -->
            <div class="timeline-item" :class="{'active': currentStage === 'summer-intensive'}">
              <div class="timeline-dot dot-orange"></div>
              <div class="timeline-date">2025年7-8月</div>
              <div class="timeline-stage">
                <span class="stage-title">暑期强化阶段</span>
                <ul class="stage-tasks">
                  <li>政治开始复习</li>
                  <li>英语/数学强化训练</li>
                  <li>专业课重点突破</li>
                  <li>参加暑期集训(可选)</li>
                </ul>
              </div>
            </div>
                
            <!-- 9月大纲发布 -->
            <div class="timeline-item" :class="{'active': currentStage === 'outline-release'}">
              <div class="timeline-dot dot-red"></div>
              <div class="timeline-date">2025年9月</div>
              <div class="timeline-stage">
                <span class="stage-title">考研大纲发布</span>
                <ul class="stage-tasks">
                  <li>关注大纲变化</li>
                  <li>调整复习重点</li>
                  <li>购买最新版复习资料</li>
                </ul>
              </div>
            </div>

            <!-- 10月网上报名 -->
            <div class="timeline-item" :class="{'active': currentStage === 'online-registration'}">
              <div class="timeline-dot dot-purple"></div>
              <div class="timeline-date">2025年10月</div>
              <div class="timeline-stage">
                <span class="stage-title">网上报名</span>
                <ul class="stage-tasks">
                  <li>中国研究生招生信息网报名</li>
                  <li>确认报考院校和专业</li>
                  <li>准备报名材料</li>
                </ul>
              </div>
            </div>
            
            <!-- 11月现场确认 -->
            <div class="timeline-item" :class="{'active': currentStage === 'on-site-confirmation'}">
              <div class="timeline-dot dot-pink"></div>
              <div class="timeline-date">2025年11月</div>
              <div class="timeline-stage">
                <span class="stage-title">现场确认</span>
                <ul class="stage-tasks">
                  <li>按要求进行现场确认</li>
                  <li>采集电子照片</li>
                  <li>确认报名信息</li>
                </ul>
              </div>
            </div>

            <!-- 12月冲刺阶段 -->
            <div class="timeline-item" :class="{'active': currentStage === 'final-sprint'}">
              <div class="timeline-dot dot-yellow"></div>
              <div class="timeline-date">2025年12月</div>
              <div class="timeline-stage">
                <span class="stage-title">冲刺阶段 & 正式考试</span>
                <ul class="stage-tasks">
                  <li>全科模拟考试训练</li>
                  <li>查漏补缺重点复习</li>
                  <li>调整心态和作息</li>
                  <li>12月最后一个周末考试</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 中间内容区域 -->
    <div class="content-area">
      <div class="welcome-section">
        <h1>欢迎使用考研真题训练系统</h1>
        <p>当前阶段: {{ currentStageName }}</p>
      </div>

      <!-- 今日任务卡片 -->
      <div class="daily-task-card">
        <div class="task-header">
          <el-icon class="task-icon"><List /></el-icon>
          <span class="task-title">今日任务 ({{ completedTaskCount }}/{{ totalTaskCount }})</span>
          <el-button 
            class="add-task-btn" 
            type="primary" 
            size="small" 
            @click="showAddTaskDialog"
            :disabled="!userId"
          >
            添加任务
          </el-button>
          <el-button 
            class="refresh-btn" 
            size="small" 
            @click="fetchTodayTasks"
            :loading="taskLoading"
          >
            刷新
          </el-button>
        </div>
        
        <div class="task-content" v-if="todayTasks.length > 0">
          <div class="task-complete-hint" v-if="allTasksCompleted">
            <el-alert
              title="恭喜！今日任务全部完成！"
              type="success"
              :closable="false"
              show-icon
            />
          </div>
          
          <div class="task-list">
            <div class="task-item" v-for="task in todayTasks" :key="task.taskId">
              <el-checkbox 
                v-model="task.status" 
                :true-label="'completed'" 
                :false-label="'pending'"
                @change="toggleTaskStatus(task.taskId, task.status)"
                class="task-checkbox"
              />
              <div class="task-info">
                <div class="task-content-text" v-if="!task.editing" :class="{'completed': task.status === 'completed'}">
                  {{ task.content }}
                </div>
                <el-input 
                  v-else
                  v-model="task.editContent" 
                  @blur="updateTaskContent(task)"
                  @keyup.enter="updateTaskContent(task)"
                  size="small"
                  autofocus
                />
                <div class="task-actions">
                  <el-button 
                    v-if="!task.editing"
                    type="text" 
                    size="small" 
                    @click="startEditTask(task)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="deleteTask(task.taskId)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="task-empty" v-else>
          <el-empty description="今日还没有计划噢">
            <el-button type="primary" @click="goToCreatePlan">点击去制定计划</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 复习进度卡片 -->
      <div class="study-progress-card">
        <div class="progress-header">
          <el-icon class="progress-icon"><DataLine /></el-icon>
          <span class="progress-title">科目复习进度</span>
          <el-button 
            class="refresh-btn" 
            size="small" 
            @click="fetchStudyProgress"
            :loading="progressLoading"
          >
            刷新
          </el-button>
        </div>
        
        <div class="progress-content" v-if="studyProgress.length > 0">
          <div class="progress-item" v-for="progress in studyProgress" :key="progress.targetSubjectId">
            <div class="subject-info">
              <span class="subject-name">{{ progress.subjectName }}</span>
              <span class="progress-percentage">{{ progress.progressPercentage }}%</span>
            </div>
            <el-progress 
              :percentage="progress.progressPercentage" 
              :color="getProgressColor(progress.progressPercentage)"
              :show-text="false"
              :stroke-width="12"
            />
            <div class="progress-details">
              <span>已覆盖章节: {{ progress.coveredChapters }}/{{ progress.totalChapters }}</span>
              <span>掌握知识点: {{ progress.masteredPoints }}/{{ progress.totalPoints }}</span>
            </div>
            <div class="progress-details">
              <span>平均得分: {{ progress.avgScore }}</span>
            </div>
          </div>
        </div>
        
        <div class="progress-empty" v-else>
          <el-empty description="暂无复习进度数据">
            <el-button type="primary" @click="goToCreatePlan">去创建计划</el-button>
          </el-empty>
        </div>
      </div>
    </div>
    
    <!-- 右侧每日一题区域 -->
    <div class="question-area">
      <!-- 每日一题卡片 -->
      <div class="daily-question-card">
        <div class="question-header">
          <el-icon class="question-icon"><Reading /></el-icon>
          <span class="question-title">每日一题</span>
          <el-button 
            class="refresh-btn" 
            size="small" 
            @click="getTodayQuestion"
            :loading="loading"
          >
            刷新
          </el-button>
        </div>
        
        <div class="question-content" v-if="currentQuestion">
          <div class="question-text">
            <div v-html="formatQuestionContent(currentQuestion.content)"></div>
          </div>
          
          <!-- 选择题选项 -->
          <div class="question-options" v-if="currentQuestion.questionType === 'single_choice'">
            <el-radio-group 
              v-model="selectedChoice" 
              class="options-group"
            >
              <el-radio 
                v-for="(option, key) in parseOptions(currentQuestion.options)" 
                :key="key"
                :label="key"
                class="option-item"
              >
                <span class="option-label">{{ key }}.</span>
                <span class="option-text" v-html="formatQuestionContent(option)"></span>
              </el-radio>
            </el-radio-group>
          </div>
          
          <!-- 填空题提示 -->
          <div class="fill-blank-hint" v-if="currentQuestion.questionType === 'fill_in_the_blank'">
            <p>请在下方输入框中填写答案</p>
            <el-input 
              v-model="fillBlankAnswer" 
              placeholder="请输入答案"
              clearable
            ></el-input>
          </div>
          
          <!-- 操作按钮区域 -->
          <div class="question-actions">
            <el-button 
              type="primary" 
              @click="handleSubmitAnswer"
              :disabled="!selectedChoice && !fillBlankAnswer"
              :loading="submitting"
            >
              提交答案
            </el-button>
            <el-button 
              type="success" 
              @click="toggleFavorite"
              :loading="favoriteLoading"
            >
              {{ isFavorite ? '取消收藏' : '收藏题目' }}
            </el-button>
            <el-button 
              type="info" 
              @click="toggleAnswer"
            >
              {{ showAnswerFlag ? '收起答案' : '查看答案' }}
            </el-button>
          </div>
          
          <!-- 答案和解析区域 -->
          <div class="answer-section" v-if="showAnswerFlag">
            <div class="answer-content">
              <p><strong>正确答案：</strong><span v-html="formatQuestionContent(answerInfo.answer || '')"></span></p>
              <p><strong>解析：</strong><span v-html="formatQuestionContent(answerInfo.analysis || '暂无解析')"></span></p>
            </div>
            <div class="answer-feedback" v-if="submissionResult">
              <el-alert
                :title="submissionResult.message"
                :type="submissionResult.success ? 'success' : 'error'"
                show-icon
                :closable="false"
              />
            </div>
          </div>
        </div>
        
        <div class="question-loading" v-else-if="loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>正在加载题目...</span>
        </div>
        
        <div class="question-empty" v-else>
          <el-empty description="暂无题目" />
        </div>
      </div>
      
      <!-- 薄弱知识点卡片 -->
      <div class="weak-points-card">
        <div class="weak-points-header">
          <el-icon class="weak-points-icon"><Warning /></el-icon>
          <span class="weak-points-title">薄弱知识点</span>
          <el-button 
            class="refresh-btn" 
            size="small" 
            @click="fetchWeakPoints"
            :loading="weakPointsLoading"
          >
            刷新
          </el-button>
        </div>
        
        <div class="weak-points-content" v-if="weakPointsData.length > 0">
          <div class="weak-points-list">
            <div 
              class="weak-point-item" 
              v-for="(item, index) in weakPointsData" 
              :key="index"
            >
              <div class="point-info">
                <span class="point-name">{{ item.knowledgePoint }}</span>
                <span class="point-count">错误次数: {{ item.errorCount }}</span>
              </div>
              <el-button 
                type="primary" 
                size="small" 
                @click="goToTraining(item.subjectId, item.knowledgeId)"
              >
                去训练
              </el-button>
            </div>
          </div>
          
          <el-pagination
            small
            layout="prev, pager, next"
            :total="weakPointsTotal"
            :page-size="weakPointsPageSize"
            :current-page="weakPointsCurrentPage"
            @current-change="handleWeakPointsPageChange"
            class="weak-points-pagination"
          />
        </div>
        
        <div class="weak-points-empty" v-else>
          <el-empty description="暂无薄弱知识点数据" />
        </div>
      </div>
    </div>

    <!-- 添加任务对话框 -->
    <el-dialog v-model="addTaskDialogVisible" title="添加今日任务" width="500px">
      <el-form :model="newTaskForm" label-width="80px">
        <el-form-item label="任务内容">
          <el-input 
            v-model="newTaskForm.content" 
            placeholder="请输入任务内容" 
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addTaskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addTask">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import { Calendar, Reading, Loading, List, DataLine, Warning } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 导入KaTeX
import 'katex/dist/katex.min.css';
import katex from 'katex';

const router = useRouter();
const userStore = useUserStore();

// ====================== LaTeX渲染相关 ======================
/* 格式化题目内容 - 使用KaTeX处理数学公式 */
const formatQuestionContent = (content) => {
  if (!content) return '';
  
  try {
    let processedContent = content
      .replace(/\\n/g, '\n')  // 处理换行符
      .replace(/\\\$/g, '###DOLLAR###')  // 临时替换转义的美元符号
      .replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
        // 处理块级数学公式 $$...$$
        try {
          return katex.renderToString(formula.trim(), {
            displayMode: true,
            throwOnError: false,
            strict: false,
            trust: true
          });
        } catch (error) {
          console.warn('KaTeX block formula error:', error, 'Formula:', formula);
          return `<span class="katex-error">$$${formula}$$</span>`;
        }
      })
      .replace(/\$([^$\n]+)\$/g, (match, formula) => {
        // 处理行内数学公式 $...$
        try {
          return katex.renderToString(formula.trim(), {
            displayMode: false,
            throwOnError: false,
            strict: false,
            trust: true
          });
        } catch (error) {
          console.warn('KaTeX inline formula error:', error, 'Formula:', formula);
          return `<span class="katex-error">$${formula}$</span>`;
        }
      })
      .replace(/###DOLLAR###/g, '$')  // 恢复转义的美元符号
      .replace(/\n/g, '<br>');  // 简单的换行处理
    
    return processedContent;
  } catch (error) {
    console.error('formatQuestionContent error:', error);
    return content.replace(/\\n/g, '<br>');
  }
};

// ====================== 用户信息 ======================
const userId = computed(() => userStore.userId);
const username = computed(() => userStore.username);
const role = computed(() => userStore.role);

// ====================== 考研阶段相关 ======================
const stages = [
  { id: 'preparation', name: '基础准备阶段', start: new Date(2025, 1, 1), end: new Date(2025, 1, 28) },
  { id: 'first-review', name: '第一轮复习', start: new Date(2025, 2, 1), end: new Date(2025, 5, 30) },
  { id: 'summer-intensive', name: '暑期强化阶段', start: new Date(2025, 6, 1), end: new Date(2025, 7, 31) },
  { id: 'outline-release', name: '考研大纲发布', start: new Date(2025, 8, 1), end: new Date(2025, 8, 30) },
  { id: 'online-registration', name: '网上报名', start: new Date(2025, 9, 1), end: new Date(2025, 9, 31) },
  { id: 'on-site-confirmation', name: '现场确认', start: new Date(2025, 10, 1), end: new Date(2025, 10, 30) },
  { id: 'final-sprint', name: '冲刺阶段', start: new Date(2025, 11, 1), end: new Date(2025, 11, 31) }
];

const currentStage = ref('');
const currentStageName = ref('');

/* 计算当前所处的考研阶段 */
function calculateCurrentStage() {
  const now = new Date();

  if (now.getFullYear() < 2025) {
    currentStage.value = 'preparation';
    currentStageName.value = '准备阶段(未开始)';
    return;
  }
  
  if (now.getFullYear() > 2025) {
    currentStage.value = 'completed';
    currentStageName.value = '已完成';
    return;
  }
  
  for (const stage of stages) {
    if (now >= stage.start && now <= stage.end) {
      currentStage.value = stage.id;
      currentStageName.value = stage.name;
      return;
    }
  }
  
  currentStage.value = 'between-stages';
  currentStageName.value = '阶段过渡期';
}

// ====================== 今日任务相关 ======================
const todayTasks = ref([]);
const taskLoading = ref(false);
const totalTaskCount = ref(0);
const completedTaskCount = ref(0);
const allTasksCompleted = ref(false);
const addTaskDialogVisible = ref(false);
const newTaskForm = ref({
  content: ''
});

// 跳转到制定计划页面
const goToCreatePlan = () => {
  router.push('/study-plan/create');
};

/* 获取今日任务 */
const fetchTodayTasks = async () => {
  if (!userId.value) return;
  
  try {
    taskLoading.value = true;
    const response = await axios.get('/tasks/today', {
      params: { userId: userId.value }
    });
    todayTasks.value = response.data.map(task => ({
      ...task,
      editing: false,
      editContent: task.content
    }));
    
    const statusResponse = await axios.get('/tasks/today/status', {
      params: { userId: userId.value }
    });
    totalTaskCount.value = statusResponse.data.total;
    completedTaskCount.value = statusResponse.data.completed;
    allTasksCompleted.value = statusResponse.data.allCompleted;
  } catch (error) {
    ElMessage.error('获取今日任务失败: ' + error.message);
  } finally {
    taskLoading.value = false;
  }
};

// 任务操作相关方法
const showAddTaskDialog = () => {
  newTaskForm.value.content = '';
  addTaskDialogVisible.value = true;
};

const addTask = async () => {
  if (!newTaskForm.value.content.trim()) {
    ElMessage.warning('请输入任务内容');
    return;
  }
  
  try {
    const response = await axios.post('/tasks', {
      userId: userId.value,
      content: newTaskForm.value.content,
      status: 'pending'
    });
    
    if (response.data > 0) {
      ElMessage.success('添加任务成功');
      addTaskDialogVisible.value = false;
      await fetchTodayTasks();
    }
  } catch (error) {
    ElMessage.error('添加任务失败: ' + error.message);
  }
};

const toggleTaskStatus = async (taskId, status) => {
  try {
    const response = await axios.patch(`/tasks/${taskId}/status`, null, {
      params: {
        userId: userId.value,
        status: status
      }
    });
    
    if (response.data > 0) {
      ElMessage.success('任务状态更新成功');
      await fetchTodayTasks();
    }
  } catch (error) {
    ElMessage.error('更新任务状态失败: ' + error.message);
    await fetchTodayTasks();
  }
};

const startEditTask = (task) => {
  task.editing = true;
  task.editContent = task.content;
};

const updateTaskContent = async (task) => {
  if (!task.editContent.trim()) {
    ElMessage.warning('任务内容不能为空');
    return;
  }
  
  try {
    const response = await axios.put('/tasks', {
      taskId: task.taskId,
      userId: userId.value,
      content: task.editContent,
      status: task.status
    });
    
    if (response.data > 0) {
      ElMessage.success('任务更新成功');
      task.content = task.editContent;
      task.editing = false;
    }
  } catch (error) {
    ElMessage.error('更新任务失败: ' + error.message);
  }
};

const deleteTask = async (taskId) => {
  try {
    const response = await axios.delete(`/tasks/${taskId}`, {
      params: { userId: userId.value }
    });
    
    if (response.data > 0) {
      ElMessage.success('任务删除成功');
      await fetchTodayTasks();
    }
  } catch (error) {
    ElMessage.error('删除任务失败: ' + error.message);
  }
};

// ====================== 复习进度相关 ======================
const studyProgress = ref([]);
const progressLoading = ref(false);

// 科目名称映射表
const subjectMap = {
  1: '高等数学',
  2: '线性代数',
  3: '概率论与数理统计',
};

/* 获取科目名称 */
const getSubjectName = (subjectId) => {
  return subjectMap[subjectId] || `科目${subjectId}`;
};

/* 获取复习进度 */
const fetchStudyProgress = async () => {
  if (!userId.value) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    progressLoading.value = true;
    const response = await axios.get(`/study-progress/${userId.value}`);
    
    if (!response.data || !Array.isArray(response.data)) {
      throw new Error('无效的响应数据');
    }
    
    // 按科目分组并计算平均值
    const subjectMap = {};
    response.data.forEach(item => {
      if (!subjectMap[item.targetSubjectId]) {
        subjectMap[item.targetSubjectId] = {
          targetSubjectId: item.targetSubjectId,
          progressPercentage: 0,
          coveredChapters: 0,
          totalChapters: 0,
          completedTasks: 0,
          totalTasks: 0,
          masteredPoints: 0,
          totalPoints: 0,
          avgScore: 0,
          count: 0
        };
      }
      const subject = subjectMap[item.targetSubjectId];
      subject.progressPercentage += item.progressPercentage || 0;
      subject.coveredChapters += item.coveredChapters || 0;
      subject.totalChapters = Math.max(subject.totalChapters, item.totalChapters || 0);
      subject.completedTasks += item.completedTasks || 0;
      subject.totalTasks += item.totalTasks || 0;
      subject.masteredPoints += item.masteredPoints || 0;
      subject.totalPoints = Math.max(subject.totalPoints, item.totalPoints || 0);
      subject.avgScore += item.avgScore || 0;
      subject.count++;
    });
    
    // 计算平均值
    studyProgress.value = Object.values(subjectMap).map(subject => ({
      targetSubjectId: subject.targetSubjectId,
      subjectName: getSubjectName(subject.targetSubjectId),
      progressPercentage: Math.round(subject.progressPercentage / subject.count),
      coveredChapters: subject.coveredChapters,
      totalChapters: subject.totalChapters,
      completedTasks: subject.completedTasks,
      totalTasks: subject.totalTasks,
      masteredPoints: subject.masteredPoints,
      totalPoints: subject.totalPoints,
      avgScore: (subject.avgScore / subject.count).toFixed(1)
    }));
    
  } catch (error) {
    const errorMsg = error.response?.data?.message || error.message;
    ElMessage.error(`获取复习进度失败: ${errorMsg}`);
    console.error('API请求详情:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      error: errorMsg
    });
  } finally {
    progressLoading.value = false;
  }
};

/* 根据进度获取颜色 */
const getProgressColor = (percentage) => {
  if (percentage >= 80) return '#67c23a';
  if (percentage >= 50) return '#e6a23c';
  return '#f56c6c';
};

/* 格式化日期 */
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};

// ====================== 每日一题相关 ======================
const currentQuestion = ref(null);
const answerInfo = ref({});
const showAnswerFlag = ref(false);
const loading = ref(false);
const favoriteLoading = ref(false);
const isFavorite = ref(false);
const fillBlankAnswer = ref('');
const selectedChoice = ref('');
const submitting = ref(false);
const submissionResult = ref(null);

/*解析选项*/
const parseOptions = (options) => {
  try {
    return JSON.parse(options);
  } catch (e) {
    console.error('解析选项失败:', e);
    return {};
  }
};

/* 获取今日题目 */
const getTodayQuestion = async () => {
  try {
    loading.value = true;
    showAnswerFlag.value = false;
    fillBlankAnswer.value = '';
    selectedChoice.value = '';
    const response = await axios.get('/daily-question/today');
    currentQuestion.value = response.data;
    await checkFavoriteStatus();
  } catch (error) {
    ElMessage.error('获取题目失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

/* 检查收藏状态 */
const checkFavoriteStatus = async () => {
  if (!userId.value || !currentQuestion.value) {
    isFavorite.value = false;
    return;
  }
  
  try {
    const response = await axios.get('/daily-question/favorite/check', {
      params: {
        userId: userId.value,
        questionId: currentQuestion.value.questionId
      }
    });
    isFavorite.value = response.data;
  } catch (error) {
    console.error('检查收藏状态失败:', error);
    isFavorite.value = false;
  }
};

/* 切换收藏状态 */
const toggleFavorite = async () => {
  if (!userId.value) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    favoriteLoading.value = true;
    if (isFavorite.value) {
      await axios.delete('/daily-question/favorite', {
        params: {
          userId: userId.value,
          questionId: currentQuestion.value.questionId
        }
      });
      ElMessage.success('已取消收藏');
    } else {
      await axios.post('/daily-question/favorite', null, {
        params: {
          userId: userId.value,
          questionId: currentQuestion.value.questionId
        }
      });
      ElMessage.success('收藏成功');
    }
    isFavorite.value = !isFavorite.value;
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message);
  } finally {
    favoriteLoading.value = false;
  }
};

/* 获取答案和解析 */
const getAnswerAndAnalysis = async () => {
  try {
    const response = await axios.get('/daily-question/answer', {
      params: {
        questionId: currentQuestion.value.questionId,
        questionType: currentQuestion.value.questionType
      }
    });
    answerInfo.value = response.data;
  } catch (error) {
    ElMessage.error('获取答案失败: ' + error.message);
    throw error;
  }
};

/* 提交答案 */
const submitAnswer = async (isCorrect) => {
  try {
    const response = await axios.post('/daily-question/submit-answer', null, {
      params: {
        userId: userId.value,
        questionId: currentQuestion.value.questionId,
        questionType: currentQuestion.value.questionType,
        answer: currentQuestion.value.questionType === 'single_choice' 
                ? selectedChoice.value 
                : fillBlankAnswer.value,
        isCorrect: isCorrect,
        score: isCorrect ? 1 : 0,
        timeSpent: 0
      }
    });
    
    return response.data;
  } catch (error) {
    console.error('提交答案出错:', error);
    throw error;
  }
};

/* 查看答案 */
const toggleAnswer = async () => {
  if (!showAnswerFlag.value) {
    try {
      await getAnswerAndAnalysis();
    } catch (error) {
      return;
    }
  }
  showAnswerFlag.value = !showAnswerFlag.value;
};

/* 处理提交答案 */
const handleSubmitAnswer = async () => {
  if (!userId.value) {
    ElMessage.warning('请先登录');
    return;
  }

  try {
    submitting.value = true;
    // 先获取正确答案
    await getAnswerAndAnalysis();
    
    // 判断答案是否正确
    let isCorrect = false;
    let userAnswer = '';
    
    if (currentQuestion.value.questionType === 'single_choice') {
      userAnswer = selectedChoice.value;
      isCorrect = userAnswer === answerInfo.value.answer;
    } else if (currentQuestion.value.questionType === 'fill_in_the_blank') {
      userAnswer = fillBlankAnswer.value.trim();
      isCorrect = userAnswer === answerInfo.value.answer.trim();
    }
    
    // 提交答案
    await submitAnswer(isCorrect);
    
    // 显示答案和解析
    showAnswerFlag.value = true;
    
    // 根据正确与否显示不同颜色的提示
    submissionResult.value = {
      success: isCorrect,
      message: isCorrect ? '答案正确！' : '答案错误！'
    };
    
    if (!isCorrect) {
      ElMessage.error('答案错误！');
    } else {
      ElMessage.success('答案正确！');
    }
  } catch (error) {
    ElMessage.error('提交答案失败: ' + error.message);
  } finally {
    submitting.value = false;
  }
};

// ====================== 薄弱知识点相关 ======================
const weakPointsData = ref([]);
const weakPointsLoading = ref(false);
const weakPointsTotal = ref(0);
const weakPointsCurrentPage = ref(1);
const weakPointsPageSize = ref(5);

/* 获取薄弱知识点 */
const fetchWeakPoints = async () => {
  if (!userId.value) return;
  
  try {
    weakPointsLoading.value = true;
    const response = await axios.get('/api/z/weak-points', {
      params: {
        userId: userId.value,
        page: weakPointsCurrentPage.value,
        size: weakPointsPageSize.value,
        subjectId: null
      }
    });

    // 字段映射
    weakPointsData.value = response.data.data.list.map(item => ({
      knowledgePoint: item.label || '未知知识点',
      errorCount: item.wrongCount || 0,
      subjectId: item.subjectId,
      knowledgeId: item.pointId
    }));
    
    weakPointsTotal.value = response.data.data.total;
  } catch (error) {
    ElMessage.error('获取薄弱知识点失败: ' + error.message);
  } finally {
    weakPointsLoading.value = false;
  }
};

/* 跳转到训练页面 */
const goToTraining = (subjectId, knowledgeId) => {
  router.push({
    path: '/training/mock-exam',
    query: {
      subjectId: subjectId,
      knowledgeId: knowledgeId
    }
  });
};

/* 分页变化处理 */
const handleWeakPointsPageChange = (page) => {
  weakPointsCurrentPage.value = page;
  fetchWeakPoints();
};

// ====================== 生命周期钩子 ======================
onMounted(() => {
  calculateCurrentStage();
  fetchTodayTasks();
  fetchStudyProgress();
  getTodayQuestion(); 
  fetchWeakPoints();
});
</script>

<style scoped>
/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 123, 255, 0.3);
  border-radius: 3px;
  transition: all 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 123, 255, 0.6);
}

::-webkit-scrollbar-corner {
  background: transparent;
}

/* Firefox滚动条 */
* {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 123, 255, 0.3) transparent;
}

/* 基础布局 */
.home-container {
  display: flex;
  height: calc(100vh - 60px);
  margin-top: 0;
  overflow: hidden;
  background-color: #fafafa;
}

/* 左侧备考进度区域 */
.progress-container {
  width: 380px;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  background: #fafafa;
  position: relative;
}

.progress-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 20px;
  background: linear-gradient(to bottom, #fafafa, transparent);
  z-index: 10;
  pointer-events: none;
}

.progress-container::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 20px;
  background: linear-gradient(to top, #fafafa, transparent);
  z-index: 10;
  pointer-events: none;
}

.progress-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
  overflow: hidden;
  position: relative;
  z-index: 5;
}

.progress-card::after {
  content: "∫ ∑ ∂ √ ∆ π ∞";
  position: absolute;
  top: 50px;
  right: -30px;
  font-size: 120px;
  color: rgba(0, 123, 255, 0.03);
  z-index: 0;
  transform: rotate(15deg);
  user-select: none;
  pointer-events: none;
  font-family: 'Times New Roman', serif;
  line-height: 0.8;
}

.progress-header,
.progress-content {
  position: relative;
  z-index: 1;
}

.progress-header {
  display: flex;
  align-items: center;
  padding: 18px 20px;
  background: #007bff;
  color: white;
}

.calendar-icon {
  color: white;
  font-size: 20px;
  margin-right: 12px;
}

.progress-title {
  font-size: 16px;
  font-weight: 600;
  color: white;
}

.progress-content {
  padding: 20px;
}

.timeline {
  position: relative;
  padding-left: 20px;
}

.timeline::before {
  content: '';
  position: absolute;
  left: 9px;
  top: 0;
  bottom: 0;
  width: 3px;
  background: #007bff;
}

.timeline-item {
  position: relative;
  margin-bottom: 25px;
  transition: all 0.3s ease;
}

.timeline-dot {
  position: absolute;
  left: -23px;
  top: 5px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  transition: all 0.3s ease;
  border: 2px solid white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.dot-blue { background-color: #007bff; }
.dot-green { background-color: #28a745; }
.dot-orange { background-color: #fd7e14; }
.dot-red { background-color: #dc3545; }
.dot-purple { background-color: #6f42c1; }
.dot-pink { background-color: #e83e8c; }
.dot-yellow { background-color: #ffc107; }

.timeline-date {
  font-weight: 600;
  margin-bottom: 8px;
  color: #495057;
  font-size: 14px;
}

.timeline-stage {
  margin-left: 10px;
  transition: all 0.3s ease;
  padding: 12px;
  border-radius: 6px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
}

.stage-title {
  font-weight: 600;
  color: #007bff;
  display: inline-block;
  margin-bottom: 8px;
  font-size: 14px;
}

.stage-tasks {
  margin: 0;
  padding-left: 16px;
  color: #6c757d;
  font-size: 13px;
}

.stage-tasks li {
  margin-bottom: 6px;
  line-height: 1.5;
}

.timeline-item.active {
  transform: translateX(3px);
}

.timeline-item.active .timeline-dot {
  transform: scale(1.2);
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.2);
}

.timeline-item.active .timeline-stage {
  background-color: #e8f4fd;
  border-color: #007bff;
}

/* 中间内容区域 */
.content-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  max-width: 800px;
  margin: 0 auto;
  background-color: #fafafa;
  position: relative;
}

.content-area::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 20px;
  background: linear-gradient(to bottom, #fafafa, transparent);
  z-index: 10;
  pointer-events: none;
}

.content-area::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 20px;
  background: linear-gradient(to top, #fafafa, transparent);
  z-index: 10;
  pointer-events: none;
}

.welcome-section {
  margin-bottom: 20px;
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
  position: relative;
  overflow: hidden;
  z-index: 5;
}

/* 其他卡片的z-index */
.daily-task-card,
.study-progress-card {
  position: relative;
  z-index: 5;
}

.daily-question-card,
.weak-points-card {
  position: relative;
  z-index: 5;
}

.welcome-section::before {
  content: "∫ f(x)dx   ∑   ∂f/∂x   √(x²+y²)   lim   ∇   ∆   ∞   π   ∮   ∏   ∈   ∀   ∃   ≤   ≥   ≠   ≈   ∴   ∵   θ   α   β   γ   λ   μ   σ   φ   ω";
  position: absolute;
  top: -10px;
  left: -20px;
  right: -20px;
  bottom: -10px;
  font-size: 48px;
  color: rgba(0, 123, 255, 0.05);
  z-index: 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: center;
  line-height: 1.2;
  letter-spacing: 10px;
  transform: rotate(-3deg);
  user-select: none;
  pointer-events: none;
  font-family: 'Times New Roman', serif;
}

.welcome-section h1,
.welcome-section p {
  position: relative;
  z-index: 1;
}

.welcome-section h1 {
  color: #2c3e50;
  margin-bottom: 12px;
  font-size: 22px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
}

.welcome-section p {
  color: #6c757d;
  margin-bottom: 0;
  font-size: 15px;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
}

/* 今日任务卡片样式 */
.daily-task-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e0e0e0;
}

.task-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 12px;
}

.task-icon {
  color: #007bff;
  font-size: 18px;
  margin-right: 10px;
}

.task-title {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  color: #2c3e50;
}

.add-task-btn {
  margin-right: 8px;
  background-color: #007bff;
  border-color: #007bff;
}

.refresh-btn {
  border-color: #6c757d;
  color: #6c757d;
}

.task-complete-hint {
  margin-bottom: 15px;
}

.task-list {
  margin-top: 10px;
}

.task-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f1f3f4;
  transition: all 0.2s;
}

.task-item:hover {
  background-color: #f8f9fa;
}

.task-item:last-child {
  border-bottom: none;
}

.task-info {
  flex: 1;
  margin-left: 12px;
  display: flex;
  align-items: center;
}

.task-content-text {
  line-height: 1.4;
  color: #495057;
  transition: all 0.3s;
  flex: 1;
  padding: 4px 0;
}

.task-content-text.completed {
  color: #6c757d;
  text-decoration: line-through;
}

.task-actions {
  margin-top: 4px;
  text-align: right;
}

.task-empty {
  padding: 30px 0;
  text-align: center;
}

/* 复习进度卡片样式 */
.study-progress-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  border: 1px solid #e0e0e0;
}

.progress-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 12px;
}

.progress-icon {
  color: #007bff;
  font-size: 18px;
  margin-right: 10px;
}

.progress-title {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  color: #2c3e50;
}

.progress-item {
  margin-bottom: 20px;
  padding: 16px;
  border-radius: 6px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  transition: all 0.3s;
}

.subject-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-weight: 500;
}

.subject-name {
  font-size: 15px;
  color: #2c3e50;
}

.progress-percentage {
  font-weight: 600;
  color: #007bff;
}

.progress-details {
  display: flex;
  justify-content: space-between;
  margin-top: 12px;
  font-size: 13px;
  color: #6c757d;
}

.plan-dates {
  margin-top: 8px;
  font-size: 12px;
  color: #adb5bd;
  text-align: right;
}

.progress-empty {
  padding: 30px 0;
}

/* 右侧每日一题区域 */
.question-area {
  width: 350px;
  padding: 20px;
  overflow-y: auto;
  background: #fafafa;
  position: relative;
}

.question-area::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 20px;
  background: linear-gradient(to bottom, #fafafa, transparent);
  z-index: 10;
  pointer-events: none;
}

.question-area::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 20px;
  background: linear-gradient(to top, #fafafa, transparent);
  z-index: 10;
  pointer-events: none;
}

/* 每日一题卡片样式 */
.daily-question-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e0e0e0;
  position: relative;
  overflow: hidden;
}

.daily-question-card::before {
  content: "?";
  position: absolute;
  top: -20px;
  right: -10px;
  font-size: 180px;
  color: rgba(0, 123, 255, 0.02);
  z-index: 0;
  font-weight: bold;
  user-select: none;
  pointer-events: none;
  font-family: 'Times New Roman', serif;
}

.question-header,
.question-content,
.question-actions,
.answer-section {
  position: relative;
  z-index: 1;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 12px;
}

.question-icon {
  color: #007bff;
  font-size: 18px;
  margin-right: 10px;
}

.question-title {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  color: #2c3e50;
}

.question-content {
  margin-top: 12px;
}

.question-text {
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 15px;
  color: #495057;
}

/* KaTeX样式优化 */
.question-text :deep(.katex) {
  font-size: 1.1em;
  line-height: 1.5;
}

.question-text :deep(.katex-display) {
  margin: 1em 0;
  text-align: center;
}

.question-text :deep(.katex-error) {
  color: #d32f2f;
  background: #ffebee;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.question-options {
  margin: 12px 0;
}

.options-group {
  width: 100%;
  margin: 12px 0;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  margin: 6px 0;
  border-radius: 6px;
  background-color: #f8f9fa;
  transition: all 0.3s;
  width: 100%;
  border: 1px solid #e9ecef;
}

.option-item:hover {
  background-color: #e8f4fd;
  border-color: #007bff;
}

.option-item.is-checked {
  background-color: #e8f4fd;
  border-color: #007bff;
}

.option-label {
  font-weight: 600;
  margin-right: 8px;
  min-width: 18px;
  color: #007bff;
}

.option-text {
  flex: 1;
  color: #495057;
}

/* 选项中的KaTeX样式 */
.option-text :deep(.katex) {
  font-size: 1em;
  line-height: 1.5;
}

.option-text :deep(.katex-display) {
  margin: 0.5em 0;
  text-align: left;
}

.fill-blank-hint {
  margin: 12px 0;
}

.fill-blank-hint p {
  color: #6c757d;
  margin-bottom: 8px;
}

.question-actions {
  margin: 20px 0;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.question-actions .el-button {
  flex: 1;
  min-width: 80px;
}

.answer-section {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 16px;
  margin-top: 15px;
  border-left: 3px solid #007bff;
}

.answer-content p {
  margin: 8px 0;
  line-height: 1.6;
  color: #495057;
}

.answer-content strong {
  color: #007bff;
}

/* 答案区域的KaTeX样式 */
.answer-content :deep(.katex) {
  font-size: 1em;
  line-height: 1.5;
}

.answer-content :deep(.katex-display) {
  margin: 0.5em 0;
  text-align: center;
}

.answer-feedback {
  margin-top: 12px;
}

.question-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
  color: #6c757d;
}

.question-loading .el-icon {
  font-size: 24px;
  margin-bottom: 12px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.question-empty {
  padding: 30px 0;
}

/* 薄弱知识点卡片样式 */
.weak-points-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  border: 1px solid #e0e0e0;
  position: relative;
  overflow: hidden;
}

.weak-points-card::after {
  content: "⚠ Δ ≠ ∅";
  position: absolute;
  bottom: -20px;
  right: -15px;
  font-size: 80px;
  color: rgba(253, 126, 20, 0.04);
  z-index: 0;
  transform: rotate(-10deg);
  user-select: none;
  pointer-events: none;
  font-family: 'Times New Roman', serif;
  letter-spacing: 8px;
}

.weak-points-header,
.weak-points-content {
  position: relative;
  z-index: 1;
}

.weak-points-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 12px;
}

.weak-points-icon {
  color: #fd7e14;
  font-size: 18px;
  margin-right: 10px;
}

.weak-points-title {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  color: #2c3e50;
}

.weak-points-content {
  margin-top: 12px;
}

.weak-points-list {
  margin: 12px 0;
}

.weak-point-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f1f3f4;
  transition: all 0.2s;
}

.weak-point-item:hover {
  background-color: #f8f9fa;
}

.weak-point-item:last-child {
  border-bottom: none;
}

.point-info {
  flex: 1;
}

.point-name {
  display: block;
  font-weight: 500;
  margin-bottom: 4px;
  color: #495057;
}

.point-count {
  font-size: 12px;
  color: #6c757d;
}

.weak-points-pagination {
  margin-top: 15px;
  justify-content: center;
}

.weak-points-empty {
  padding: 30px 0;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .home-container {
    flex-direction: column;
    height: auto;
  }
  
  .progress-container, .content-area, .question-area {
    width: 100%;
    max-width: none;
    padding: 15px;
  }
  
  .content-area {
    order: 1;
  }
  
  .progress-container {
    order: 2;
  }
  
  .question-area {
    order: 3;
  }
}

/* 数学公式动画效果 */
@keyframes mathFloat {
  0%, 100% { 
    transform: rotate(-3deg) translateY(0px); 
    opacity: 0.05; 
  }
  50% { 
    transform: rotate(-3deg) translateY(-2px); 
    opacity: 0.08; 
  }
}

@keyframes progressMath {
  0%, 100% { 
    transform: rotate(15deg) translateX(0px); 
    opacity: 0.03; 
  }
  50% { 
    transform: rotate(15deg) translateX(2px); 
    opacity: 0.05; 
  }
}

@keyframes questionMark {
  0%, 100% { 
    transform: scale(1) rotate(0deg); 
    opacity: 0.02; 
  }
  50% { 
    transform: scale(1.02) rotate(1deg); 
    opacity: 0.04; 
  }
}

.welcome-section::before {
  animation: mathFloat 8s ease-in-out infinite;
}

.progress-card::after {
  animation: progressMath 10s ease-in-out infinite;
}

.daily-question-card::before {
  animation: questionMark 6s ease-in-out infinite;
}

/* 卡片统一动画效果 */
.progress-card, .daily-task-card, .study-progress-card, 
.daily-question-card, .weak-points-card {
  transition: transform 0.3s, box-shadow 0.3s;
}

.progress-card:hover, .daily-task-card:hover, .study-progress-card:hover, 
.daily-question-card:hover, .weak-points-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}

/* KaTeX全局样式优化 */
:deep(.katex) {
  overflow-x: auto;
  overflow-y: hidden;
  max-width: 100%;
}

:deep(.katex-display) {
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0.5em 0;
}

/* 确保KaTeX在所有容器中都能正确显示 */
:deep(.katex .mord),
:deep(.katex .mrel),
:deep(.katex .mop),
:deep(.katex .mbin),
:deep(.katex .mpunct),
:deep(.katex .mopen),
:deep(.katex .mclose) {
  color: inherit;
}
</style>